package wangjg.coco.module;

import java.io.File;
import java.util.ArrayList;
import java.util.List;

import org.eclipse.core.resources.IFile;
import org.eclipse.core.resources.IFolder;
import org.eclipse.core.resources.IResource;
import org.eclipse.jdt.core.IJavaProject;

import wangjg.coco.PDUtil;
import wangjg.coco.common.AstModelContext;
import wangjg.coco.views.ExplorerPreferencePage;
import wangjg.mda.context.ModelContext;
import wangjg.mda.context.SourceContext;
import wangjg.mda.gen.Generator;
import wangjg.mda.model.obj.Model;

public class BasicProcessor extends Generator {
	private List<IResource> resourceList;
	
	public BasicProcessor() {
	}
	
	protected ModelContext getModelContext(){
		String srcCharset = PDUtil.getCharset();
		List<IFile> list = this.getFileList();
		IJavaProject jproject = PDUtil.getJavaProject(list.get(0));
		List<String> sourceRoots = PDUtil.getSourceRoots(jproject);
		
		SourceContext context = null;
		String fullClassName = ExplorerPreferencePage.getCodeParser();
		if(fullClassName!=null && fullClassName.length()>0){
			context = new AstModelContext();
			this.toolBox.put("code-parser", "ast");
		}
		if(context==null){
			context = new SourceContext();
			this.toolBox.put("code-parser", "wjg");
		}
		context.setDirList(sourceRoots);
		context.setCharset(srcCharset);
		return context;
	}
	
	protected List<Model> getModelList(){
		List<Model> modelList = new ArrayList<Model>();
		List<IFile> list = this.getFileList();
		ModelContext context = this.getModelContext();
		for(IFile iFile:list){
			try {
				File file = iFile.getLocation().toFile();
				String charset = iFile.getCharset();
				context.setCharset(charset);
				
				Model model = context.loadModel(file);
				modelList.add(model);
			} catch (Exception e) {
				e.printStackTrace();
			}
		}
		return modelList;
	}
	
	protected List<IFile> getFileList(){
		List<IFile> list = new ArrayList<IFile>();
		IResource[] a = new IResource[resourceList.size()];
		resourceList.toArray(a);
		try {
			this.getFileList(a, list);
		} catch (Exception e) {
			e.printStackTrace();
		}
		return list;
	}
	
	private void getFileList(IResource[] resources, List<IFile> outList) throws Exception{
		for(IResource resource:resources){
			if(resource instanceof IFile){
				outList.add((IFile) resource);
			}else if(resource instanceof IFolder){
				IFolder folder = (IFolder)resource;
				IResource[] members = folder.members();
				getFileList(members, outList);
			}
		}
	}

	public void setResourceList(List<IResource> resourceList) {
		this.resourceList = resourceList;
	}

}
